package org.droid.campusorder.view;

import java.util.Timer;
import java.util.TimerTask;
import org.droid.R;
import org.droid.campusorder.MainActivity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

public class ViewAboutAD extends ViewGroup {
	private Scroller mScroller;
	private VelocityTracker mVelocityTracker;
	private int mScrollX = 0;
	private int mCurrentScreen = 0;
	private float mLastMotionX;
	private static final String LOG_TAG = "DragableSpace";
	private static final int SNAP_VELOCITY = 1000;
	private final static int TOUCH_STATE_REST = 0;
	private final static int TOUCH_STATE_SCROLLING = 1;
	private int mTouchState = TOUCH_STATE_REST;
	private int mTouchSlop = 0;
	
	private Timer timer;
	private int ADItemCurrentPisition;
	public static String[] drawableResources= null;
	
	public static String[] getDrawableResources() {
		return drawableResources;
	}
	
	public static void setDrawableResources(String[] drawableResources) {
		ViewAboutAD.drawableResources = drawableResources;
	}

	public ViewAboutAD(Context context) {
		super(context);
		mScroller = new Scroller(context);
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();

		this.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.FILL_PARENT));
		autoPlay();
	}


	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		/*
		 * *这种方法只是决定我们是否想拦截运动。如果我们还真,onTouchEvent必称为和我们做实际的滚动
		 * 我们用case来完成当用户用手指来完成拖拽时开始拦截
		 */
		final int action = ev.getAction();
		if ((action == MotionEvent.ACTION_MOVE)
				&& (mTouchState != TOUCH_STATE_REST)) {
			return true;
		}

		final float x = ev.getX();
		switch (action) {
		case MotionEvent.ACTION_MOVE:
			/*
			 * *mIsBeingDragged = =假,
			 */
			final int xDiff = (int) Math.abs(x - mLastMotionX);
			boolean xMoved = xDiff > mTouchSlop;

			if (xMoved) {
				// Scroll if the user moved far enough along the X axis
				mTouchState = TOUCH_STATE_SCROLLING;
			}
			break;
		case MotionEvent.ACTION_DOWN:
			// Remember location of down touch
			mLastMotionX = x;

			/*
			 * * 如果被flinged和用户触动屏幕上启动
			 */
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
					: TOUCH_STATE_SCROLLING;
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			// Release the drag
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		/*
		 * * 我们唯一的一次想拦截移动事件是我们在拖动模式。
		 */
		return mTouchState != TOUCH_STATE_REST;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);

		final int action = event.getAction();
		final float x = event.getX();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			Log.i(LOG_TAG, "event : down");
			/*
			 * * 如果被flinged和用户的触摸,停止fling.结束
			 */
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}
			mLastMotionX = x;
			break;
		case MotionEvent.ACTION_MOVE:
			// Scroll to follow the motion event
			final int deltaX = (int) (mLastMotionX - x);
			mLastMotionX = x;

			if (deltaX < 0) {
				scrollBy(deltaX, 0);
			} else if (deltaX > 0) {
				scrollBy(deltaX, 0);
			}

			break;
		case MotionEvent.ACTION_UP:
			Log.i(LOG_TAG, "event : up");
			final VelocityTracker velocityTracker = mVelocityTracker;
			velocityTracker.computeCurrentVelocity(1000);
			int velocityX = (int) velocityTracker.getXVelocity();
			if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
				// Fling hard enough to move left
				snapToScreen(mCurrentScreen - 1);
			} else if (velocityX < -SNAP_VELOCITY
					&& mCurrentScreen < getChildCount() - 1) {
				// Fling hard enough to move right
				snapToScreen(mCurrentScreen + 1);
			} else if (mCurrentScreen == getChildCount() - 1) {
				snapToScreen(mCurrentScreen);
			} else {
				snapToDestination();
			}

			if (mVelocityTracker != null) {
				mVelocityTracker.recycle();
				mVelocityTracker = null;
			}
			mTouchState = TOUCH_STATE_REST;
			break;
		case MotionEvent.ACTION_CANCEL:
			Log.i(LOG_TAG, "event : cancel");
			mTouchState = TOUCH_STATE_REST;
		}
		mScrollX = this.getScrollX();
		return true;
	}

	private void snapToDestination() {
		final int screenWidth = getWidth();
		final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth;
		Log.i(LOG_TAG, "from des");
		snapToScreen(whichScreen);
	}

	public void snapToScreen(int whichScreen) {
		Log.i(LOG_TAG, "snap To Screen " + whichScreen);
		mCurrentScreen = whichScreen;
		final int newX = whichScreen * getWidth();
		final int delta = newX - mScrollX;
		mScroller.startScroll(mScrollX, 0, delta, 0, Math.abs(delta) * 2);
		chagePointHandler.sendEmptyMessage(whichScreen);
		invalidate();
	}

	public void setToScreen(int whichScreen) {
		Log.i(LOG_TAG, "set To Screen " + whichScreen);
		mCurrentScreen = whichScreen;
		final int newX = whichScreen * getWidth();
		mScroller.startScroll(newX, 0, 0, 0, 10);
		invalidate();
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int childLeft = 0;
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			final View child = getChildAt(i);
			if (child.getVisibility() != View.GONE) {
				final int childWidth = child.getMeasuredWidth();
				child.layout(childLeft, 0, childLeft + childWidth,
						child.getMeasuredHeight());
				childLeft += childWidth;
			}
		}

	}

	
	// 接受childview的请求的大小，然后通过childview的measure(widthMeasureSpec,widthMeasureSpec)函数存储到childview中去，
	//以便childView的getMeasuredWidth() 和getMeasuredHeight() 的值可以被后续工作得到。
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		final int width = MeasureSpec.getSize(widthMeasureSpec);
		final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		if (widthMode != MeasureSpec.EXACTLY) {
			//不注释将抛出异常= =！
//			throw new IllegalStateException("error mode.");
		}

		final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		if (heightMode != MeasureSpec.EXACTLY) {
			//不注释将抛出异常= =！
//			throw new IllegalStateException("error mode.");
		}

		// The children are given the same width and height as the workspace
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}
		Log.i(LOG_TAG, "moving to screen " + mCurrentScreen);
		scrollTo(mCurrentScreen * width, 0);
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			mScrollX = mScroller.getCurrX();
			scrollTo(mScrollX, 0);
			postInvalidate();
		}
	}
	
	// 实现自我播放功能
	protected void autoPlay() {
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override 
			public void run() {
				if (ADItemCurrentPisition < drawableResources.length - 1) {
					ADItemCurrentPisition = ADItemCurrentPisition + 1;
				} else {
					ADItemCurrentPisition = 0;
				}
				MainActivity.autoPlayHandler.sendEmptyMessage(ADItemCurrentPisition);
			}
		}, 6000, 6000); 
	}
	
	public static Handler chagePointHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			for (int i = 0; i < ViewAboutAD.drawableResources.length; i++) {
				if (i == msg.what) {
					MainActivity.images[i].setImageResource(R.drawable.point_sel);
				} else {
					MainActivity.images[i].setImageResource(R.drawable.point);
				}
			}
		}
	};
	
	public Timer getTimer() {
		return timer;
	}
	
	public void closeTimer(){
		timer.cancel();
	}

}